package cn.itcast.bos.web.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.WayBillService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {

	// 需求：将保存的运单存放到log4j的日志文件中
	Logger logger = Logger.getLogger(WayBillAction.class);

	@Autowired
	private WayBillService wayBillService;

	// 保存，ajax执行保存，尽量返回页面提示的信息，否则页面看起来无操作，体验不好
	@Action(value="waybill_save",results={@Result(name="success",type="json")})
	public String save(){
		// 防止瞬时对象异常，如果WayBill对象中关联的Order对象，如果Order不为null，且id为null，此时将Order对象置null
		if(model.getOrder()!=null && (model.getOrder().getId()==null || model.getOrder().getId()==0)){
			model.setOrder(null);
		}
		Map<String, Object> map = new HashMap<String,Object>();
		try {
			wayBillService.save(model);
			map.put("success", true);
			map.put("msg", "快速保存运单成功");
			logger.info("保存运单数据成功！运单号是"+model.getWayBillNum());
		} catch (Exception e) {
			map.put("success", false);
			e.printStackTrace();
			logger.info("保存运单数据失败！运单号是"+model.getWayBillNum());
		}
		ServletActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}

	// 查询
	@Action(value="waybill_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows,new Sort(new Sort.Order(Sort.Direction.ASC, "id")));
		//查询所有从数据库中查询
//		Page<WayBill> page = wayBillService.findAll(pageable);
		//调用业务层进行查询
		Page<WayBill> page = wayBillService.findAll(model,pageable);
		pushPageDataToValueStack(page);
		return SUCCESS;
	}

	// 使用运单号，查询运单的数据，完成表单回显
	@Action(value="waybill_findByWayBillNum",results={@Result(name="success",type="json")})
	public String findByWayBillNum(){
		Map<String, Object> map = new HashMap<String,Object>();
		String wayBillNum = model.getWayBillNum();
		// 运单号唯一
		WayBill wayBill = wayBillService.findByWayBillNum(wayBillNum);
		if(wayBill==null){
			map.put("success", false);
		}
		else{
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}
		ServletActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
}
